package top.lingkang.screen;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import top.lingkang.MyGdxGame;

import java.util.Timer;
import java.util.TimerTask;


public class WelcomeScreen extends GameScreen {

    private MyGdxGame game;
    // 类似 javafx 的 Stage 我们绘制的画面在它上面
    private Stage stage;
    private Label start;
    private Music startMusic;

    public WelcomeScreen(final MyGdxGame game) {
        this.game = game;
        stage = game.stage;
        Label.LabelStyle font = new Label.LabelStyle(game.bitmapFont, Color.WHITE);
        start = new Label("Click anywhere to start the game", font);
        start.setPosition(100, 400);
        stage.addActor(start);

        game.assetManager.load("music/sml.mp3", Music.class);
        game.assetManager.finishLoading();
        startMusic = game.assetManager.get("music/sml.mp3", Music.class);
        startMusic.setLooping(true);
        startMusic.setVolume(0.4f);
        startMusic.play();
    }


    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.draw();
        if (Gdx.input.isTouched() || Gdx.input.isKeyPressed(Input.Keys.ANY_KEY)) {
            System.out.println("start game!");
            Gdx.app.log("WelcomeScreen", "start game!");
            // 进入玩游戏场景
            game.setScreen(new PlayScreen(game));
            dispose();
        }
    }

    @Override
    public void dispose() {
        super.dispose();
        stage.dispose();
        // 背景音乐音量下降
        Timer tv = new Timer();
        tv.schedule(new TimerTask() {
            @Override
            public void run() {
                startMusic.setVolume(startMusic.getVolume() - 0.025f);
            }
        }, 0, 1000);
        // 关闭背景音乐
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                startMusic.stop();
                game.assetManager.unload("music/sml.mp3");
                startMusic.dispose();
                tv.cancel();
                timer.cancel();
            }
        }, 10000);
    }
}
